package com.admin.system.service;

import com.admin.base.Page;
import com.admin.system.entity.SystemRole;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.admin.system.common.SystemConstant;
import com.admin.system.dao.SystemRoleMapper;
import com.admin.system.vo.query.SystemRoleQuery;

@Service
public class SystemRoleService {
	@Autowired
	SystemRoleMapper roleMapper;

	public SystemRole queryById(Integer id) {
		return roleMapper.selectByPrimaryKey(id);
	}

	/**
	 * 分页查询
	 * 
	 * @return
	 */
	public Page<SystemRole> paging(SystemRoleQuery query) {
		return roleMapper.paging(query);
	}

	public Integer pageCount(SystemRoleQuery query) {
		return roleMapper.pageCount(query);
	}

	public void add(SystemRole record) {
		roleMapper.insertSelective(record);
	}

	public void delete(Integer[] ids) {
		for (Integer id : ids) {
			roleMapper.deleteByPrimaryKey(id);
		}
	}

	public void update(SystemRole record) {
		roleMapper.updateByPrimaryKey(record);
	}

	public void updateStatus(SystemRole user) {
		roleMapper.updateByPrimaryKeySelective(user);
	}

	/**
	 * 获取已分配的角色
	 * 
	 * @param userId
	 * @return
	 */
	public List<SystemRole> assignedRole(Integer userId) {
		List<SystemRole> roles = roleMapper.querySystemRole(SystemConstant.RoleStatus.USABLE.getCode());
		Integer roleId = roleMapper.assignedId(userId);
		for (SystemRole systemRole : roles) {
			if (systemRole.getId().equals(roleId)) {
				systemRole.setChecked(true);
			}
		}
		return roles;
	}

	/**
	 * 重新分配角色
	 * 
	 * @param userId
	 * @param roleId
	 */
	public void assignRole(Integer userId, Integer roleId) {
		Integer assignedRole = roleMapper.assignedId(userId);
		if (!roleId.equals(assignedRole)) {
			roleMapper.assignRole(userId, roleId);
		}
	}
}
